package com.github.freegeese.maven.plugin.autocode;

import com.github.freegeese.maven.plugin.autocode.configuration.JdbcConnection;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;

/**
 * Created by Administrator on 2017/3/31.
 */
public abstract class DatabaseUtils {
    /**
     * 获取数据库连接
     *
     * @param jdbcConnection
     * @return
     */
    public static Connection getConnection(JdbcConnection jdbcConnection) {
        try {
            Class.forName(jdbcConnection.getDriver());
            Connection connection = DriverManager.getConnection(jdbcConnection.getUrl(), jdbcConnection.getUser(), jdbcConnection.getPassword());
            Properties clientInfo = jdbcConnection.getClientInfo();
            if (null != clientInfo) {
                connection.setClientInfo(clientInfo);
            }
            return connection;
        } catch (SQLException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 关闭数据库连接
     *
     * @param connection
     */
    public static void closeConnection(Connection connection) {
        try {
            if (null != connection) {
                connection.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

}
